package cn.tanghom.app.oa.controller;

import cn.tanghom.app.oa.model.Leave;
import cn.tanghom.app.oa.service.LeaveService;
import cn.tanghom.app.system.model.User;
import cn.tanghom.support.page.Pager;
import cn.tanghom.support.utils.CommonUtils;

import org.activiti.conf.CommonKey;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

import java.util.*;

/**
 * 请假控制层,基于mybatis实现的LeaveService
 *
 * @author tanghom
 */
@Controller("leave2Controller")
@RequestMapping("/oa/leave2")
public class LeaveController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;
    @Resource
    private ProcessEngine processEngine;
    @Resource
    private IdentityService identityService;
    @Resource
    private LeaveService leaveService;
    
    @RequestMapping(value = "/apply",method =RequestMethod.GET)
    public ModelAndView createForm() {
        ModelAndView mav = new ModelAndView(CommonKey.WEB_PATH + "/oa/leave/apply");
        mav.addObject("leave", new Leave());
        return mav;
    }

    @RequestMapping(value = "/apply", method =RequestMethod.POST)
    @ResponseBody
    public String apply(Leave leave) {
        try {
            User loger = CommonUtils.getUserSession();
            leave.setUser(loger);
            leave.setApplyTime(new Date());
            Map<String, Object> variables = new HashMap<String, Object>();
            ProcessInstance processInstance = leaveService.startWorkflow(leave, variables);
            return CommonUtils.msgCallback(true, "流程已启动", "", processInstance.getId());
        } catch (ActivitiException e) {
            if (e.getMessage().indexOf("no processes deployed with key") != -1) {
                return CommonUtils.msgCallback(false, "系统内部错误，请联系管理员（没有部署流程，请在[工作流]->[流程管理]页面点击<重新部署流程>），" + e.getMessage(), "", null);
            } else {
                return CommonUtils.msgCallback(false, "系统内部错误,请联系管理员（启动请假流程失败），" + e.getMessage(), "", null);
            }
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "系统内部错误,请联系管理员，" + e.getMessage(), "", null);
        }
    }


    /**
     * 任务列表
     *
     */
    @RequestMapping(value = "/my_apply")
    public ModelAndView myTaskList(Long pageNo) {
        ModelAndView mav = new ModelAndView(CommonKey.WEB_PATH + "/oa/leave/my-apply-list");
        // 根据当前人的ID查询      
        Pager<Leave> page = new Pager<Leave>();
        page.setIndex(pageNo);
        User loger = CommonUtils.getUserSession();      
        page = leaveService.findPageByParams(loger.getLoginName(),1, 1L);
       
        page.setTotalRecord(page.getTotalRecord());     
        mav.addObject("page", page);
        return mav;
    }
    

    /**
     * 任务列表
     *
     */
    @RequestMapping(value = "/task/list")
    public ModelAndView taskList(Long pageNo) {
        ModelAndView mav = new ModelAndView(CommonKey.WEB_PATH + "/oa/leave/task-list");
        // 根据当前人的ID查询
        List<Leave> leaves = new ArrayList<Leave>();
        Pager<Leave> page = new Pager<Leave>();
        page.setIndex(pageNo);
        User loger = CommonUtils.getUserSession();
        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(loger.getLoginName());
        List<Task> tasks = taskQuery.listPage(page.startRow().intValue(),page.getSize());
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
            if(processInstance == null){
            	continue;
            }
            String businessKey = processInstance.getBusinessKey();
            if (businessKey == null) {
                continue;
            }
            Leave leave = leaveService.findById(Long.parseLong(businessKey));
            if (leave == null) {
                continue;
            }
            leave.setTask(task);
            leave.setProcessInstance(processInstance);
            leaves.add(leave);
        }
        page.setTotalRecord(taskQuery.count());
        page.setItems(leaves);
        mav.addObject("page", page);
        return mav;
    }

    /**
     * 签收任务
     */
    @RequestMapping(value = "/task/claim/{id}")
    @ResponseBody
    public String claim(@PathVariable("id") String taskId) {
        try {
            User loger = CommonUtils.getUserSession();
            taskService.claim(taskId, loger.getLoginName());
            return CommonUtils.msgCallback(true, "签收任务成功", "", null);
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "系统内部错误,请联系管理员，" + e.getMessage(), "", null);

        }
    }
    

    /**
     * 读取详细数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail/{id}")
    @ResponseBody
    public Leave getLeave(@PathVariable("id") Long id) {
        Leave leave = leaveService.findById(id);
        return leave;
    }

    /**
     * 读取详细数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail-with-vars/{id}/{taskId}")
    @ResponseBody
    public Leave getLeaveWithVars(@PathVariable("id") Long id, @PathVariable("taskId") String taskId) {
        Leave leave = leaveService.findById(id);
        Map<String, Object> variables = taskService.getVariables(taskId);
        leave.setVariables(variables);
        return leave;
    }
    
    /**
     * 办理任务
     *
     * @param taskId
     * @return
     */
    @RequestMapping(value = "/task/complete/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String complete(@PathVariable("id") String taskId) {
        try {
            Map<String, Object> variables = new HashMap<String, Object>();
            variables.put("deptLeaderPass",true);
            variables.put("hrPass",true);
            taskService.complete(taskId,variables);
            return CommonUtils.msgCallback(true, "办理任务任务成功", "", null);
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "系统内部错误,请联系管理员，" + e.getMessage(), "", null);
        }
    }

}
